package cn.lzd.mr.me;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * Created by lzd on 2019/6/12.
 * 资质处理
 */
public class Cercate {
    public static class MyMapper extends Mapper<Object, Text, Text, IntWritable> {
        Text outKey = new Text();
        IntWritable outVal = new IntWritable(1);

        @Override
        protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            String string = value.toString();
            string = string.replaceAll("http://","");
            int i = string.indexOf("/");
            if(i !=-1){
                string = string.substring(0,i);
            }
            outKey.set(string);
            context.write(outKey, outVal);
        }
    }

    public static class MyReduce extends Reducer<Text, IntWritable, Text, IntWritable> {
        IntWritable outVal = new IntWritable();

        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int count = 0;
            for (IntWritable value : values) {
                count += value.get();
            }
            outVal.set(count);
            context.write(key, outVal);
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Configuration configuration = new Configuration();
        Job job = Job.getInstance(configuration);
        job.setJarByClass(Cercate.class);

        job.setMapperClass(Cercate.MyMapper.class);
        job.setReducerClass(Cercate.MyReduce.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        FileInputFormat.setInputPaths(job, new Path("G:\\图片水印\\cercateall.log"));
        FileOutputFormat.setOutputPath(job, new Path("G:\\图片水印\\out"));

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
